<template>
  <div class="app-container documentation-container">
    <div class="graph_wrapper" id="graph_wrapper">
      <div :class="{ example: true }" id="example">
        <div :class="{ graph_title: true, long: detail.provinceName && detail.provinceName.length > 6 }">
          {{ projectName }}
          <span style="float: right; cursor: pointer;" @click="hideMax">关闭</span>
        </div>
        <div id="myMap"  width="600px" hight="800px" class="exampleMap"> </div>
      </div>

    </div>
  </div>
</template>

<script>
import L from "leaflet";
import "leaflet/dist/leaflet.css";

import { myProjectDetail, movePoint, customerProjectDetail } from '@/api/myProject'
import { transformFromGCJToWGS, transformFromWGSToGCJ } from './WSCoordinate'
export default {
  name: 'Documentation',
  data() {
    return {
      map: null,
      zoomLevel: 4,
      isAdmin: this.$store.state.user.roles.includes('admin'),
      projectId: null,
      projectName: this.$route.params.name,
      detail:  { projectName: '北京'},
      mapObj: {},
      projects: sessionStorage.getItem("projectsAdmin")? JSON.parse(sessionStorage.getItem("projectsAdmin")) : {},
      mapObj: { projectId: 'a', city: '江西省', points: ['115.832058,28.714894', '116.421922,29.247737', '115.75502,27.76481', '115.019128,29.03372']},
      blueIcon: null,
      greenIcon: null,
      yellowIcon: null,
      redIcon: null,
      dredIcon: null,
      pColors:{
        0: this.greenIcon,
        1: this.blueIcon,
        2: this.yellowIcon, // 黄色
        3: this.redIcon,
        4: this.dredIcon
      }

    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMarkersData() {
      let projectDetail = {...this.projects}
      if(this.isAdmin){
        myProjectDetail(this.projectId).then(res => {
          this.detail = {
            ...projectDetail,
            points: res.data,
          }
          this.renderMarkers()
        }).catch()
      } else {
        customerProjectDetail({projectId: this.projectId }).then(res => {
          this.detail = {
            ...projectDetail,
            points: res.data,
          }
          this.renderMarkers()
        }).catch()
      }
      // this.renderMarkers()
    
    },
    renderMarkers(){
      this.detail.points.map((p, i) => {
        
        if(p.longitude && p.latitude){
          let lng = parseFloat(p.longitude), lat = parseFloat(p.latitude)
          // 把火星坐标转化为wgs84
          let wgs84Position = transformFromGCJToWGS(lat, lng)
          // console.log(wgs84Position, 'wgs84Position')
          if(i == Math.floor(this.detail.points.length/2) ){
            this.map.setView(new L.LatLng(wgs84Position.latitude, wgs84Position.longitude), 13)
          }

            let img = this.pColors[p.dataStatus]
            const myIcon = L.icon({
              iconUrl: img,
              iconSize: [25, 30],
              // iconAnchor: [22, 94],
              iconAnchor: [0, 0],
              popupAnchor: [13, 0],
              // shadowUrl: "my-icon-shadow.png",
              // shadowSize: [68, 95],
              // shadowAnchor: [22, 94],
            });
            const marker = L.marker(new L.LatLng(wgs84Position.latitude, wgs84Position.longitude), {
            icon: myIcon,
            draggable: this.$store.state.user.accountType == 0,
            // draggable: true,
            }).addTo(this.map);
                // 添加拖拽结束的事件监听器
            //  _this.dragStartPoint = new L.LatLng(lat, lng);
              marker.on("dragend", (e) => {
                  let marker = e.target;
                  let position = marker.getLatLng();
                // console.log("新位置：", position, );
                // 把wgs84 转换为火星坐标传给后台
                let resPosition = transformFromWGSToGCJ(position.lat, position.lng)
                movePoint({
                    deviceId: p.id,
                    longitude: resPosition.longitude,
                    latitude: resPosition.latitude
                }).then(res => {
                    if(res.statusCode == '200') {
                    this.$message.success('重新定位成功！')
                    }
                }).catch()
              });

            marker.on("click", (e) => {
              marker.unbindPopup();
              const elements = this.getProjectPopupContent(p);
              marker.bindPopup(elements).openPopup(e.latlng);
            });

            }

        })
    },
    initMap() {
      this.greenIcon = '/imgs/marker1.png'  
      this.blueIcon =  "/imgs/marker2.png"  
      this.yellowIcon = "/imgs/marker3.png"  
      this.redIcon = "/imgs/marker4.png"  
      this.dredIcon = "/imgs/marker5.png"  
      this.pColors ={
        0: this.greenIcon,
        1: this.blueIcon,
        2: this.yellowIcon, // 黄色
        3: this.redIcon,
        4: this.dredIcon
      }

    let width = document.body.clientWidth - 200 * 1
    let height = document.body.clientHeight - 130
    document.getElementById('graph_wrapper').style.width = width + 'px'
    document.getElementById('graph_wrapper').style.height = height + 'px'

    this.timer = null;

    const tdtKey = "a60e29bb7b4f94344345b038205fe71f";
    this.map = L.map("myMap", {
        crs: L.CRS.EPSG4326,
        center: [34.26, 108.96],
        // center: [39.89329, 116.39151],
        zoom: this.zoomLevel,
        maxZoom: 17, //最大缩放层级
        minZoom: 1, //最小缩放层级
        tileSize: 256, //切片大小
        attributionControl: false, // 移除右下角leaflet标识
        zoomControl: false, //禁用 + - 按钮
        // maxBounds: "bounds", //设置边界
        preferCanvas: true, //默认使用svg渲染，设置canvas渲染
        doubleClickZoom: false, //关闭双击缩放
        // dragging: false, //鼠标移动事件
    });

    // 添加缩放结束的事件监听器
    this.map.on("zoomend", (e) => {
        // console.log("Zoom ended", e);
        // 缩放结束时的逻辑
        var zoomLevel = this.map.getZoom(); // 获取当前缩放级别
        console.log("Current zoom level:", zoomLevel);
    });
    // 影像图
    const img = L.tileLayer(
        "http://t0.tianditu.gov.cn/img_c/wmts?tk=" +
        tdtKey +
        "&layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        {
        crossOrigin: "anonymous",
        tileSize: 256,
        zoomOffset: 1,
        noWrap: true,
        }
    );

    // 影像注记
    const cia = L.tileLayer(
        "http://t0.tianditu.gov.cn/cia_c/wmts?tk=" +
        tdtKey +
        "&layer=cia&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        {
        crossOrigin: "anonymous",
        tileSize: 256,
        zoomOffset: 1,
        noWrap: true,
        }
    );
    // 矢量图
    const vec = L.tileLayer(
        "http://t0.tianditu.gov.cn/vec_c/wmts?tk=" +
        tdtKey +
        "&layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        {
        crossOrigin: "anonymous",
        tileSize: 256,
        zoomOffset: 1,
        noWrap: true,
        }
    );

    // 矢量注记
    const cva = L.tileLayer(
        "http://t0.tianditu.gov.cn/cva_c/wmts?tk=" +
        tdtKey +
        "&layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        {
        crossOrigin: "anonymous",
        tileSize: 256,
        zoomOffset: 1,
        noWrap: true,
        }
    );

    const vector = L.layerGroup([vec, cva]);
    const image = L.layerGroup([img, cia]);

    const baseLayers = {
        矢量: vector,
        影像: image,
    };

    // 初始化显示矢量图层

    // this.map.addLayer(vector);
    this.map.addLayer(image);

    // 创建并添加缩放控件
    L.control
        .zoom({
        position: "bottomright", // 可以设置为'topleft', 'topright', 'bottomleft' 或 'bottomright'
        })
        .addTo(this.map);

    // 创建并添加尺寸控件
    L.control
        .scale({
        position: "bottomleft",
        maxWidth: 200,
        metric: true, // 显示公制尺寸
        imperial: true, // 显示英制尺寸
        })
        .addTo(this.map);
    // 添加图层控件;
    L.control.layers(baseLayers).addTo(this.map).setPosition("bottomright");

    this.initMarkersData();
    },
    getProjectPopupContent: (item) => {
      let elements = `<div class="infowindow" style="line-height: 20px;">
          <div style="font-weight: bold; margin-bottom: 4px;"> <span class="title" style="margin-right: 6px">设备名称： </span> <span class="value"> ${item.deviceName} </span> </div>
          <div> <span class="title" style="margin-right: 6px">IMEI： </span> <span class="value"> ${item.imei} </span> </div>
          <div> <span class="title" style="margin-right: 6px">自定义编码： </span> <span class="value"> ${item.deviceCode} </span> </div>
          <div> <span class="title" style="margin-right: 6px">安装时间： </span> <span class="value"> ${item.insTime} </span> </div>
          </div>`
          // <div> <span class="title" style="margin-right: 6px">电子标签： </span> <span class="value"> ${item.rfid} </span> </div>
          // <div> <span class="title" style="margin-right: 6px">经度： </span> <span class="value"> ${item.longitude} </span> </div>
          // <div> <span class="title" style="margin-right: 6px">维度： </span> <span class="value"> ${item.latitude} </span> </div>
      return elements;
    },
 
    hideMax(){
      this.$router.push('/project/projectAdmin')
    }
  },
  created(){
    this.projectId = this.$route.params.id

  }
  
}
</script>

<style lang="scss" >
.hide {
  visibility: hidden;
}
.graph_wrapper {
  position: relative;
}
.example {

  width: 100%;
  height: calc( 100% - 60px);
  background: #0B1120;
  padding: 30px 50px;
  background: #0B1120 url('../../assets/imgs/mapBg.png') no-repeat;
  background-size: 100% 100%;
  .graph_title {
    color: #fff;
    font-size: 14px;
    background: url('../../assets/imgs/map_title_small.png') no-repeat;
    // background-size: 100% 100%;
    padding: 5px 20px;
    margin-bottom: 20px;
    &.long {
      background: url('../../assets/imgs/map_title_long.png') no-repeat;
    }
  }
  .exampleMap {
    width: 100%;
    height: calc( 100% - 100px);
    // height: 100%;
    touch-action:none
  }
}



.documentation-container {
  // margin: 0 20px;
  // padding: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  position: relative;

  .document-btn {
    flex-shrink: 0;
    display: block;
    cursor: pointer;
    background: black;
    color: white;
    height: 60px;
    padding: 0 16px;
    margin: 16px;
    line-height: 60px;
    font-size: 20px;
    text-align: center;
  }
}
</style>
